package com.superwein.springcloud.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.superwein.springcloud.gateway.domain.AjaxResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class AuthorizeGatewayFilterFactory extends AbstractGatewayFilterFactory<Object> {

    private static Map<String, String> map = new HashMap<>();

    /**
     * 程序启动的时候加载权限的信息，比如从文件、数据库中加载
     */
    static {
        map.put("jack", "123456");
    }

    /**
     * 简单判断
     *
     * @param name
     * @param password
     * @return
     */
    public static boolean isPermitted(String name, String password) {
        return map.containsKey(name) && map.get(name).equals(password);
    }

    public AuthorizeGatewayFilterFactory() {
        super();
        log.info("Loaded RoutePredicateFactory [Authorize]");
    }

    @Override
    public GatewayFilter apply(Object config) {
        return (exchange, chain) -> {
            // 获取header的参数
            String name = exchange.getRequest().getHeaders().getFirst("username");
            String password = exchange.getRequest().getHeaders().getFirst("password");
            // 权限比较
            boolean permitted = isPermitted(name, password);
            if (permitted) {
                return chain.filter(exchange);
            } else {
                ServerHttpResponse response = exchange.getResponse();
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
                return exchange.getResponse().writeWith(
                        Mono.just(response.bufferFactory().
                                wrap(JSON.toJSONBytes(AjaxResult.fail(
                                        HttpStatus.UNAUTHORIZED.value(), "没有访问权限")))));
            /*exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();*/
            }
        };
    }

}
